import * as echarts from "echarts";
import styles from '../../assets/css/ChineseWesternMedicine/RevenueDataTable.module.css';
import { useEffect, useRef, useState } from 'react';
import { getInfomationcenter } from '../../api/ChineseWesternMedicine/RevenueDataTable';
import { Table } from "antd";

export default function RevenueDataTable() {
  const chartRef = useRef(null);
  const chartRef1 = useRef(null);
  const [weightChart, setWeightChart] = useState([]);
  const [otherdata, setOtherData] = useState([]);
  const [tabledata, setTableData] = useState([]);

  const getDataLeft = async () => {
    const res = await getInfomationcenter({});
    const tableWithKey = res.data.table.map((item, index) => ({
      ...item,
      key: item.id || index, // 如果有 id 字段，用 id；否则用索引 index 作为备用
    }));
    setTableData(tableWithKey);
    setWeightChart(res.data.weightChart.data);
    setOtherData(res.data.departmentChart.otherData); // 获取部门饼图数据
  };


  useEffect(() => {
    getDataLeft();
  }, []);

  useEffect(() => {
    let chartInstance = echarts.init(chartRef.current);
    let chartInstance1 = echarts.init(chartRef1.current);

    const seriesData = [
      {
        name: '内科综合',
        type: 'bar',
        stack: 'total',
        label: { show: true },
        emphasis: { focus: 'series' },
        data: weightChart.map(item => item['内科综合'])
      },
      {
        name: '外科综合',
        type: 'bar',
        stack: 'total',
        label: { show: true },
        emphasis: { focus: 'series' },
        data: weightChart.map(item => item['外科综合'])
      },
      {
        name: '超声科',
        type: 'bar',
        stack: 'total',
        label: { show: true },
        emphasis: { focus: 'series' },
        data: weightChart.map(item => item['超声科'])
      }
    ];

    // 手动定义一个颜色数组
    const colorArray = [
      '#FFB6C1', '#FF6347', '#FFD700', '#9ACD32', '#8A2BE2', '#00CED1', '#FF69B4', '#DC143C'
    ];

    // 处理饼图数据并为每个数据项分配颜色
    const pieData = otherdata.map((item, index) => ({
      value: item.value,
      name: item.name,
      color: colorArray[index % colorArray.length] // 根据索引分配颜色
    }));

    const pieDataHandle = (data) => {
      data.sort((a, b) => b.value - a.value);
      return data.map(item => ({ value: item.value, name: item.name }));
    };

    // 饼图配置
    const option1 = {
      backgroundColor: "#FFF",
      color: pieData.map(el => el.color), // 饼图部分颜色，动态根据传入的 pieData 设置
      legend: {
        show: true,
        icon: 'roundRect', // 设置图例的形状为圆角长方形
        orient: 'horizontal',
        top: 'top',
        right: '20%',
        itemWidth: 12, // 图例宽度缩小
        itemHeight: 12, // 图例高度缩小
        itemGap: 8, // 图例项之间的间距
        data: pieData.map(el => el.name),
        textStyle: {
          padding: [0, 0, 0, 10],
          fontSize: 12, // 调整图例字体大小
          color: '#40C5F1'
        }
      },
      series: [
        {
          type: 'pie',
          roseType: 'radius',
          radius: ['15%', '70%'],
          center: ['45%', '50%'],
          data: pieDataHandle(pieData),
          hoverAnimation: false,
          itemStyle: {
            normal: {
              borderWidth: 1,
              borderColor: '#fff',  // 设置边框颜色
              borderRadius: 10  // 设置圆角效果},

            },
            labelLine: { length: 0 },
            label: {
              show: true,
              padding: [0, 20, 0, 0],
              formatter: params => {
                return '{name|' + params.name + params.value + '}';
              },
              rich: {
                name: { fontSize: 16, color: '#000' }
              }
            },
            emphasis: {
              focus: 'self',
              label: {
                show: true,
                padding: [0, 10, 0, 0],
                formatter: params => {
                  return [
                    `{aName|${params.name}}\n` +
                    `{household|${params.value}}` +
                    `{discount|人数}\n\n`
                  ];
                },
                rich: {
                  aName: { fontSize: 16, color: '#a6e4ff' },
                  household: { fontSize: 18, color: '#a6e4ff' },
                  discount: { fontSize: 16, color: '#a6e4ff' }
                }
              },
              itemStyle: {
                shadowBlur: 30,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
                borderColor: '#000',
                borderWidth: 1
              }
            }
          }
        }
      ]
    };

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {},
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
      },
      yAxis: {
        type: 'category',
        data: ['本周权重', '本月权重', '季度权重', '年度权重']
      },
      series: seriesData,
      barCategoryGap: '50%'
    };

    chartInstance.setOption(option);
    chartInstance1.setOption(option1);
    // 清理工作：组件卸载时销毁图表实例
    return () => {
      if (chartInstance) {
        chartInstance.dispose();
      }
      if (chartInstance1) {
        chartInstance1.dispose();
      }
    };
  }, [weightChart, otherdata]);

  const columns = [
    {
      title: '住院部',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '本周服务医务数',
      dataIndex: 'server',
      key: 'server',
    },
    {
      title: '金额',
      dataIndex: 'money',
      key: 'money',
    },
    {
      title: '上周金额',
      dataIndex: 'lastweek',
      key: 'lastweek',
    },
    {
      title: '本月金额',
      dataIndex: 'month',
      key: 'month',
    },
    {
      title: '审计人员',
      dataIndex: 'audit',
      key: 'audit',
    },
    {
      title: '负责人',
      dataIndex: 'chargeperson',
      key: 'chargeperson'
    }
  ];
  return (
    <div className={styles.body}>
      <div className={styles.charts}>
        <div ref={chartRef} style={{ height: "100%", width: '50%', display: 'flex', justifyContent: 'center' }}></div>
        <div ref={chartRef1} style={{ height: "100%", width: '50%', display: 'flex', justifyContent: 'center' }}></div>
      </div>
      <Table title={() => <h1 className={styles.title}>详情数据</h1>} dataSource={tabledata} pagination={false} columns={columns} size="small" />
    </div>
  );
}
